package com.franklin.ideaplugin.easytesting.spring.invoke;

import cn.hutool.core.util.StrUtil;
import com.franklin.ideaplugin.easytesting.common.entity.MethodInvokeData;
import com.franklin.ideaplugin.easytesting.controllerclient.utils.ControllerUtil;
import com.franklin.ideaplugin.easytesting.common.constants.EasyTestingHeaders;
import com.franklin.ideaplugin.easytesting.core.invoke.IMethodInvoker;
import com.franklin.ideaplugin.easytesting.spring.config.MyServerProperties;
import com.franklin.ideaplugin.easytesting.spring.utils.SpringUtil;
import lombok.RequiredArgsConstructor;

import java.lang.reflect.Method;

/**
 * @author Ye Junhui
 * @since 2023/6/30
 */
@RequiredArgsConstructor
class ControllerClientMethodInvoker implements IMethodInvoker {

    private final MyServerProperties myServerProperties;

    @Override
    public Object invoke(MethodInvokeData methodInvokeData, Class<?> targetClass, Method targetMethod, Class<?>[] paramTypes, Object[] params) throws Exception {
        //获取controller-client
        String clientClazzName = ControllerUtil.getClientClazzName(targetClass);
        Class<?> clientClazz = Class.forName(clientClazzName);
        Class<?>[] realParamTypes = ControllerUtil.getControllerMethodParameterTypes(targetMethod);
        Method declaredMethod = clientClazz.getDeclaredMethod(ControllerUtil.getClientMethodName(targetMethod), realParamTypes);
        declaredMethod.setAccessible(true);
        Object bean = SpringUtil.getBean(clientClazz);

        //方法参数
        //请求地址
        String targetUrl = myServerProperties.getServerPath();
        String prefix = myServerProperties.getPrefix();
        String rewriteUrl = methodInvokeData.getHeaderMap().get(EasyTestingHeaders.HTTP_URL_REWRITE);
        if (StrUtil.isNotBlank(rewriteUrl)){
            targetUrl = rewriteUrl + prefix;
        }
        Object[] proxyMethodParameters = ControllerUtil.getProxyMethodParameters(methodInvokeData, targetUrl,targetMethod);
        return declaredMethod.invoke(bean,proxyMethodParameters);
    }

}
